package com.guaoran.source.zookeeper.config;

import com.guaoran.source.zookeeper.anno.RpcAnnotation;
import com.guaoran.source.zookeeper.common.ServiceRegisterCenter;
import com.guaoran.source.zookeeper.common.StringUtils;
import com.guaoran.source.zookeeper.thread.ProcessThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/14 12:22
 */
public class OrderServerConfig {
    //服务地址
    private String serviceAddress;
    //服务注册中心
    private ServiceRegisterCenter serviceRegisterCenter;
    //用来存放服务名称和服务地址
    Map<String,Object> registerCenterMap = new HashMap<>();
    //使用线程池
    ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(5,20,4, TimeUnit.SECONDS,new LinkedBlockingDeque<>());

    public OrderServerConfig(String serviceAddress, ServiceRegisterCenter serviceRegisterCenter) {
        this.serviceAddress = serviceAddress;
        this.serviceRegisterCenter = serviceRegisterCenter;
    }

    /**
     * 注册服务
     * @param services
     */
    public void registerCenter(Object... services){
        //遍历服务，存放到注册中心中，
        for (Object service : services) {
            RpcAnnotation annotation = service.getClass().getAnnotation(RpcAnnotation.class);
            if(annotation==null){
                continue;
            }
            String serviceName = annotation.value().getName();
            String version = annotation.version();
            //版本不为空
            if (StringUtils.isNotEmpty(version)) {
                serviceName += "-" + version;
            }
            registerCenterMap.put(serviceName,service);
        }

    }
    /**
     * 发布服务
     */
    public void publisherServer(){
        ServerSocket serverSocket = null;
        try {
            if(StringUtils.isEmpty(serviceAddress)){
                throw new RuntimeException("服务地址为空");
            }
            String[] hostAndPort = serviceAddress.split(":");
            //将服务发布的zookeeper中
            for (String serviceName:registerCenterMap.keySet()) {
                serviceRegisterCenter.registerCenter(serviceName,serviceAddress);
                System.out.println("服务发布到zookeeper成功-->"+serviceName+"/"+serviceAddress);
            }
            //启动一个监听
            serverSocket = new ServerSocket(Integer.parseInt(hostAndPort[1]));
            System.out.println("服务端开始监听请求");
            while(true){
                //开始监听
                Socket socket = serverSocket.accept();
                threadPoolExecutor.execute(new ProcessThread(socket,registerCenterMap));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
